import datetime

import requests

key_map = {
    "Log Decoration": "itm_log_decoration2",
    "Empty Barrel": "itm_barrel01",
    "Barrel of Purple": "itm_barrel03",
    "Wooden Stool": "itm_Wooden_Stool",
    "Whittlewood Plank": "itm_woodplank_01",
    "Whittlewood Log": "itm_woodlog_01",
    "Crafting Mix": "itm_craftingPowder",
    "Stick": "itm_stick",
    "Blue Grumpkin": "itm_grumpkinFruit",
}

def get_average_price(item_name):
    pid = '660519964c130305f729d2c3'
    now = datetime.datetime.now()
    ts = now.timestamp() * 1000
    item_id = key_map.get(item_name)
    url = f'https://pixels-server.pixels.xyz/v1/marketplace/item/{item_id}?pid={pid}&v={ts}'
    resp = requests.get(url)
    listings = resp.json().get('listings', [])
    amount = 0
    count = 0
    for row in listings:
        if row['state'] == 'active':
            qty = row['quantity']
            price = row['price']
            amount += price * qty
            count += qty
    return round(amount / count, 0)

def get_floor_price(item_name, threshold=1):
    pid = '660519964c130305f729d2c3'
    now = datetime.datetime.now()
    ts = now.timestamp() * 1000
    item_id = key_map.get(item_name)
    url = f'https://pixels-server.pixels.xyz/v1/marketplace/item/{item_id}?pid={pid}&v={ts}'
    resp = requests.get(url)
    listings = resp.json().get('listings', [])
    for row in listings:
        qty = row['quantity']
        if qty < threshold:
            continue
        return row['price']
    return 0

if __name__ == "__main__":
    avg_price = get_average_price('Stick')

    print(avg_price)
